package com.hrm.controller;

import com.hrm.entity.Document;
import com.hrm.entity.User;
import com.hrm.service.njh.DocumentService;
import com.hrm.utils.Constants;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * 文件管理
 *
 * @author 李雪阳
 * @version 1.0
 * @date 2020/8/1 17:01
 */
@Controller
public class DocumentController {
    @Autowired
    DocumentService documentService;

    @GetMapping("/document")
    public String text() {
        return "document/add";
    }

    /**
     * 添加文件
     *
     * @return
     */
    @PostMapping("/addDocument")
    public ModelAndView addDocument(Document document, @RequestParam(required = false) MultipartFile file, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        view.setViewName("document/add");
        String remarkPath = null;
        long l = System.currentTimeMillis();
        Date date = new Date(l);
        document.setCreateDate(date);
        Integer id = (Integer) request.getSession().getAttribute("id");
        document.setCuid(id);
        if (!file.isEmpty()) {
            int fileSeze = 5000000;
            if (file.getSize() > fileSeze) {
                view.addObject("ex", "文件大小超过限制");
                return view;
            }
            String oldFilaName = file.getOriginalFilename();
            String extens = FilenameUtils.getExtension(oldFilaName).toUpperCase();
            if (extens.equals("DOX") || extens.equals("XLS") || extens.equals("XLSX") || extens.equals("DOCX")) {
                //文件保存路径
                String path = "D:/images";
                //String path = request.getSession().getServletContext().getRealPath("statics");
                String fileName = System.currentTimeMillis() + "_remark." + oldFilaName;
                File newfile = new File(path, fileName);
                if (!newfile.exists()) {
                    newfile.mkdir();
                }
                try {
                    file.transferTo(newfile);
                } catch (IOException e) {
                    e.printStackTrace();
                    view.addObject("ex", "文件上传失败");
                    return view;
                }
                remarkPath = path + File.separator + fileName;
            } else {
                view.addObject("ex", "文件类型不匹配");
                return view;
            }
        }
        document.setRemark(remarkPath);
        document.setModifyDate(date);
        document.setMuid(1);
        int i = documentService.addDocument(document);

        return view;
    }

    /**
     * 查询 加上模糊查询
     *
     * @param filename
     * @return
     */
    @GetMapping("/selectDocumentList")
    public ModelAndView selectDocumentList(String filename) {
        System.out.println("123");
        ModelAndView view = new ModelAndView();
        view.setViewName("document/list");
        List<Document> documents = documentService.selectDocumentList(filename);
        view.addObject("documents", documents);
        return view;
    }

    @GetMapping("deletedocument")
    @ResponseBody
    public String deletedocument(@RequestParam("id") Integer id) {
        System.out.println("22222222222222");
        int deletedocument = documentService.deletedocument(id);
        return "document/list";
    }


    /**
     * 文件下载功能
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping("fileDown")
    public String fileDown(@RequestParam(value = "remark") String remark, HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream out;
        //得到要下载的文件
        File file = new File(remark);
        try {
            //设置响应头，控制浏览器下载该文件
            response.setContentType("multipart/form-data");
            //获得浏览器信息,并处理文件名
            String headerType = request.getHeader("User-Agent").toUpperCase();
            String fileName = null;
            if (headerType.indexOf("EDGE") > 0 || headerType.indexOf("MSIE") > 0 || headerType.indexOf("GECKO") > 0) {
                fileName = URLEncoder.encode(file.getName(), "UTF-8");
            } else {
                fileName = new String(file.getName().replaceAll(" ", "").getBytes("utf-8"), "iso8859-1");
            }
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Length", "" + file.length());
            FileInputStream inputStream = new FileInputStream(file);

            out = response.getOutputStream();

            int b = 0;
            byte[] buffer = new byte[1024];
            while (b != -1) {
                b = inputStream.read(buffer);
                //写到输出流(out)中
                if (b != -1) {
                    out.write(buffer, 0, b);
                }
            }
            inputStream.close();
            out.close();//关闭输出流
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "doment/list";
    }


}
